package com.jetbrains.crack.controllers;

import com.jetbrains.crack.FXOptionPane;
import com.jetbrains.crack.TextUtils;
import com.rover12421.crack.jerbrains.ClionPatch;
import com.rover12421.crack.jerbrains.GenericKeyMaker;
import com.rover12421.crack.jerbrains.Rover12421Main;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.stage.FileChooser;

import javax.swing.*;
import java.io.File;
import java.net.URL;
import java.util.ResourceBundle;

/**
 * Created by plter on 8/5/15.
 */
public class MainFormController implements Initializable{
    public TextField tfRegName;
    public TextField tfClionPath;
    public ToggleGroup group;
    public RadioButton rbClion;
    public HBox vbBrowseForJar;
    public HBox root;
    public RadioButton rbIdea;
    public RadioButton rbWebStorm;
    public RadioButton rbPhpStorm;
    public RadioButton rbPyCharm;
    public RadioButton rbRubyMine;
    public RadioButton rbAppCode;
    public TextArea taKeyOutput;

    private File clionJarFile = null;


    @Override
    public void initialize(URL location, ResourceBundle resources) {
        listenToggleGroup();
    }

    private void listenToggleGroup() {
        group.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
            @Override
            public void changed(ObservableValue<? extends Toggle> observable, Toggle oldValue, Toggle newValue) {
                boolean currentIsClion = newValue == rbClion;

                vbBrowseForJar.setVisible(currentIsClion);
                vbBrowseForJar.setManaged(currentIsClion);
            }
        });
    }

    public void browseForClionJarPath(ActionEvent actionEvent) {
        FileChooser fc = new FileChooser();
        fc.setTitle("浏览clion.jar文件");
        clionJarFile = fc.showOpenDialog(root.getScene().getWindow());
        if (clionJarFile!=null) {
            if (clionJarFile.getAbsolutePath().toLowerCase().endsWith(".app")) {
                clionJarFile = new File(clionJarFile, "Contents/lib/clion.jar");
            }

            if (clionJarFile.exists()) {
                tfClionPath.setText(clionJarFile.getAbsolutePath());
            }else {
                clionJarFile = null;
                tfClionPath.setText("");
            }
        }else {
            tfClionPath.setText("");
        }
    }

    public void genRegCode(ActionEvent actionEvent) {
        if (!rbClion.isSelected()){
            genNormalKey();
        }else {
            genClionKey();
        }
    }

    private void genNormalKey(){
        String regName = tfRegName.getText();

        if (TextUtils.isEmpty(regName)){
            FXOptionPane.showMessageDialog(root.getScene().getWindow(),"注册名不能为空","提示");
            return;
        }

        if (rbIdea.isSelected()){
            outputProductKeyToTextArea(Rover12421Main.Product.Idea,regName,taKeyOutput);
        }else if (rbAppCode.isSelected()){
            outputProductKeyToTextArea(Rover12421Main.Product.AppCode,regName,taKeyOutput);
        }else if (rbPhpStorm.isSelected()){
            outputProductKeyToTextArea(Rover12421Main.Product.PhpStorm,regName,taKeyOutput);
        }else if (rbPyCharm.isSelected()){
            outputProductKeyToTextArea(Rover12421Main.Product.PyCharm,regName,taKeyOutput);
        }else if (rbRubyMine.isSelected()){
            outputProductKeyToTextArea(Rover12421Main.Product.RubyMine,regName,taKeyOutput);
        }else if (rbWebStorm.isSelected()){
            outputProductKeyToTextArea(Rover12421Main.Product.WebStorm,regName,taKeyOutput);
        }
    }

    private void genClionKey(){
        if (clionJarFile==null){
            FXOptionPane.showMessageDialog(root.getScene().getWindow(),"请先选择clion文件","提示");
            return;
        }

        if (!clionJarFile.exists()){
            FXOptionPane.showMessageDialog(root.getScene().getWindow(),"所选择的clion文件不存在","提示");
            return;
        }

        final String regName = tfRegName.getText();
        if (TextUtils.isEmpty(regName)){
            FXOptionPane.showMessageDialog(root.getScene().getWindow(),"注册名不能为空","提示");
            return;
        }

        taKeyOutput.setText("如果你正在运行CLion，请关闭\n正在执行破解并且生成key，请稍候...");

        new Thread(){
            @Override
            public void run() {
                try {
                    if (!ClionPatch.patch(clionJarFile.getAbsolutePath())) {

                        Platform.runLater(() -> {
                            taKeyOutput.setText("");
                            FXOptionPane.showMessageDialog(root.getScene().getWindow(), "clion.jar文件错误，请重新选择", "提示");
                        });
                    }else {
                        Platform.runLater(() -> {
                            outputProductKeyToTextArea(Rover12421Main.Product.Clion, regName, taKeyOutput);
                        });
                    }
                } catch (Exception e1) {
                    e1.printStackTrace();

                    Platform.runLater(()->{
                        taKeyOutput.setText("");
                        FXOptionPane.showMessageDialog(root.getScene().getWindow(), "破解失败或者所选择的clion.jar文件错误，请重新选择", "提示");
                    });
                }
            }
        }.start();
    }

    private void outputProductKeyToTextArea(Rover12421Main.Product product,String regName,TextArea output){
        GenericKeyMaker keyMaker = new GenericKeyMaker();
        if (product.isRSA()) {
            output.setText(keyMaker.generateRSAKey(product.getPrivKey(), product.getPubKey(), GenericKeyMaker.LICENSETYPE_NON_COMMERCIAL, product.getProductId(), 1, 13, regName));
        } else {
            output.setText(keyMaker.generateNoRSAKey(product.getPrivKey(), product.getPubKey(), GenericKeyMaker.LICENSETYPE_NON_COMMERCIAL, product.getProductId(), 1, 14, regName));
        }
    }
}
